package com.sy.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sy.UserService;
import com.sy.constant.MessageConstant;
import com.sy.constant.StatusConstant;
import com.sy.dto.UserLoginDTO;
import com.sy.dto.UserPageQueryDTO;
import com.sy.mapper.UserMapper;
import com.sy.pojo.User;
import com.sy.result.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    // 用户端登录
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        //  1.根据手机号查询用户
        queryWrapper.eq(User::getPhone, userLoginDTO.getPhone());
        User user = this.getOne(queryWrapper);
        if (user == null){
            throw new RuntimeException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //2.前台获取到的密码进行加密
        String password = DigestUtils.md5DigestAsHex(userLoginDTO.getPassword().getBytes());
        // 密码比对
        if (!password.equals(user.getPassword())){
            throw new RuntimeException(MessageConstant.PASSWORD_ERROR);
        }
        //3.判断账号是否被锁定
        if (user.getStatus() == StatusConstant.DISABLE){
            throw new RuntimeException(MessageConstant.ACCOUNT_LOCKED);
        }
        //4.判断账号是否被注销
        if (user.getIsDelete() == StatusConstant.DISABLE){
            throw new RuntimeException("您的账号已被注销");
        }
        return user;
    }


    // 用户分页查询
    @Override
    public PageResult findAll(UserPageQueryDTO userPageQueryDTO) {
        //设置分页参数
        Page<User> page = new Page<>(userPageQueryDTO.getPage(), userPageQueryDTO.getPageSize());
        //设置查询条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(userPageQueryDTO.getName()),
                User::getName, userPageQueryDTO.getName())
                .select(User.class, info->!info.getColumn().equals("password"));
        page = this.page(page, queryWrapper);
        return new PageResult(page.getTotal(), page.getRecords());
    }
}
